package com.huazai.juc.cec.thread.july.twentyOne;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

@Slf4j
public class MessageQueue {
    private LinkedList<Message> list = new LinkedList<>();
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    public Message take() {
        // 同步代码块 synchronized， 等下再回来试试final行不行
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    log.info(Thread.currentThread().getName() + "-------------队列为空，消费者线程等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Message message = list.removeFirst();
            log.info(Thread.currentThread().getName() + "：已经消费消息--" + message);
            list.notifyAll();
            return message;
        }
    }

    public void put(Message message) {
        synchronized (list) {
            while (list.size() == capacity) {
                try {
                    log.info(Thread.currentThread().getName() + "-----------队列已满，生产者线程等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(message);
            log.info(Thread.currentThread().getName() + ":已经生产消息-- " + message);
            list.notifyAll();
        }
    }
}